import { useUserInfoStore, useIndexStore } from '@/store/index';
import { getVideoUrl, baseGetRequest } from "./api";
import { submitUserInfo } from "@/common/api/user";
import { uploadDistParams, uploadParamsAPI } from "@/common/api";
import { getUploadImageParams } from "@/common/api/api";
import { tencentMetroAPI } from '@/common/api/houses';
import { truncateDecimals } from './utils/tax-tools';

String.prototype.startswith = function(str) {
    return this.substr(0, str.length) === str;
};

//验证用户是否授权手机号登录
export function checkLogin() {
    let userInfo = uni.getStorageSync('userInfo');
    return userInfo.is_login
}

//验证用户是否授权头像和昵称
export function checkUserInfo() {
    let userInfo = uni.getStorageSync('userInfo');
    return userInfo.login
}

//验证用户是否手机号登录
export function checkIsLogin() {
    let userInfo = uni.getStorageSync('userInfo');
    return userInfo.is_login
}

//验证用户是否授权隐私政策
export function checkAgreementPrivacy() {
    let userInfo = uni.getStorageSync('userInfo');
    return userInfo.privacy
}

/**
 * 验证是否有通讯方式。手机号、微信号
 * @param type {String} phone手机号  wx微信号
 */
export function checkHasContactID(type) {
    const userInfoStore = useUserInfoStore();
    let userInfo = userInfoStore.userInfo;
    if(type == 'phone') {
        return userInfo.phone?true:false
    }else {
        return userInfo.wx_id?true:false
    }
}

function get_query_string(param) {
  let vars = {};
  window.location.href.replace( location.hash, '' ).replace(
    /[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
    function( m, key, value ) { // callback
      vars[key] = value !== undefined ? value : '';
    }
  );

  if ( param ) {
    return vars[param] ? vars[param] : '';
  }
  return vars;
}

/**
 * UTC格式转换为年/月/日/ 时:分:秒
 */
export function utc2local(utcString) {
	if(!utcString){
		return ''
	}
	let time = new Date(utcString);
	return time.toLocaleString('china', {hour12: false})
}

/**
 * @ desc 格式化时间
 * @ time 时间对象 { object | string | number } 
 * @ cFormat 精确到某一位
 * @ return 时间
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
  let date
  if (typeof time === 'object') {
    date = time
  } else {
      //yy-mm-dd hh:mm:ss格式转化为标准时间
    if (typeof time === 'string') {
        date = new Date(Date.parse(time.replace(/-/g, "/")))
    }
    //时间戳格式转化为标准时间
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000;
      date = new Date(time)
    }
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

//2020-20-20 12:00转换成标准时间
export function parserDate (date) {
    var t = Date.parse(date);
    if (!isNaN(t)) {
        return new Date(Date.parse(date.replace(/-/g, "/")));
    } else {
        return new Date(Date.parse(date.replace(/-/g, "/")));
    }
}

/**
 * Number formatting
 * like 10000 => 10k
 * @param {number} num
 * @param {number} digits
 */
export function numberFormatter(num, digits) {
  const si = [
    { value: 1E18, symbol: 'E' },
    { value: 1E15, symbol: 'P' },
    { value: 1E12, symbol: 'T' },
    { value: 1E9, symbol: 'G' },
    { value: 1E6, symbol: 'M' },
    { value: 1E3, symbol: 'k' }
  ]
  for (let i = 0; i < si.length; i++) {
    if (num >= si[i].value) {
      return (num / si[i].value).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + si[i].symbol
    }
  }
  return num.toString()
}

//比较是否在指定时间范围内
export function isDuringDate(beginDateStr, endDateStr) {
    let curDate = new Date();
    let beginDate = beginDateStr ? parserDate(beginDateStr) : 0;
    let endDate = endDateStr ? parserDate(endDateStr) : 0;
    if(beginDateStr === endDateStr) {
        curDate = parserDate(`${curDate.getFullYear()}-${curDate.getMonth()+1}-${curDate.getDate()}`)
    }
    if(curDate < beginDate) {
        return 'before'
    }else if (curDate >= beginDate && curDate <= endDate) {
        return 'ongoing'
    }else{
        return 'end';
    }
}

//等额本息,计算每月还款金额
//每月还本付息=【贷款本金x月利率x（1+月利率）^还款月数】/【（1+月利率）^还款月数-1】
export function benxiMonthPay(info){
    let {amount, rate=0.0465, months } = info;
    if(amount == 0){
        return 0
    }
    return amount*(rate/12*Math.pow((1+rate/12), months)) / (Math.pow((1+rate/12), months)-1);
}

//等额本息，计算总利息
//贷款额X贷款月数x月利率x（1+月利率）^还款月数/【（1+还款月数）^还款月数-1】-贷款总额
export function benXiTotalInterest(info){
    let {amount, rate=0.0465, months } = info;
    if(amount == 0){
        return 0
    }
    return amount*months*rate/12*Math.pow((1+rate/12), months) / (Math.pow((1+rate/12), months)-1) - amount;
}

/**
 * @desc 计算每月还款月利率
 * 月利率 = 贷款利率 / 12
 * @param info {Object} 还款信息
 * @param info.rate {Number} 贷款利率
 * @return {Number} 每月还款利率
 * 
 * */
export function calculateMonthRate(info) {
    let { rate } = info;
    return rate / 12
}

/**
 * @desc 计算每月还款利息
 * 剩余本金*月利率
 * @param info {Object} 还款信息
 * @param info.amount {Number} 剩余本金
 * @param info.rate {Number} 贷款利率
 * @return {Number} 每月还款利息
 * 
 * */
export function calculateMonthInterest(info) {
    return info.amount*calculateMonthRate(info)
}

//等额本息，月供本金
//每月还款金额-月供利息
export function benXiMonthsBenjin(info) {
    let { monthPay, monthInterest } = info;
    return monthPay - monthInterest
}

/**
 * 等额本息，生成每个月的还款计划,包含每月还款金额、每月还款利息、每月还款本金、剩余还款金额
 * @param info {Object} 还款信息
 * @param info.amount {Number} 贷款金额
 * @param info.months {Number} 还款月数
 * @param info.rate {Number} 贷款利率
 * @return {Object} 每个月的还款计划
 * @return {Object.monthPay} {Number} 每月还款金额
 * @return {Object.monthInterest} {Number} 每月还款利息
 * @return {Object.monthRate} {Number} 每月还款利率
 * @return {Object.monthBenjin} {Number} 每月还款本金
 * @return {Object.remainingAmount} {Number} 每月剩余还款金额
*/
export function benXiMonthPlan(info) {
    if(info.amount == 0 || info.months == 0 || info.rate == 0){
        return []
    }
    let {amount, months, rate} = info;
    let monthPlan = [];
    let monthRate = calculateMonthRate(info);
    let monthPay = benxiMonthPay(info);
    for(let i = 0; i < months; i++) {
        //每月还款利息
        let monthInterest = calculateMonthInterest({
            amount: i > 0 ? monthPlan[i-1].remainingAmount : Number(amount),
            rate: rate
        });
        
        //每月还款本金
        let monthBenjin = benXiMonthsBenjin({
            monthPay: monthPay,
            monthInterest: monthInterest
        });

        //剩余未还本金
        let remainingAmount = i > 0 ? monthPlan[i-1].remainingAmount - monthBenjin : Number(amount) - monthBenjin;

        monthPlan.push({
            month: i + 1,
            monthPay: truncateDecimals(monthPay, 2),
            monthRate: monthRate,
            monthInterest: truncateDecimals(monthInterest, 2),
            monthBenjin: truncateDecimals(monthBenjin, 2),
            remainingAmount: truncateDecimals(remainingAmount > 0 ? remainingAmount : 0, 2)
        })
    }
    console.log(monthPlan)
    return monthPlan;
}

//等额本金，生成每个月的还款计划,包含每月还款金额、每月还款利息、每月还款本金、剩余还款金额
export function benJinMonthPlan(info) {
    if(info.amount == 0 || info.months == 0 || info.rate == 0){
        return []
    }
    let {amount, months, rate} = info;
    let monthPlan = [];
    let monthBenjin = amount / months;
    let monthRate = calculateMonthRate(info);
    let monthPay = 0;
    for(let i = 0; i < months; i++) {
        let monthInterest = calculateMonthInterest({
            amount: i > 0 ? monthPlan[i-1].remainingAmount : Number(amount),
            rate: rate
        });
        monthPay = monthBenjin + monthInterest;
        let remainingAmount = i > 0 ? monthPlan[i-1].remainingAmount - monthBenjin : Number(amount) - monthBenjin;
        monthPlan.push({
            month: i + 1,
            monthPay: truncateDecimals(monthPay, 2),
            monthRate: monthRate,
            monthInterest: truncateDecimals(monthInterest, 2),
            monthBenjin: truncateDecimals(monthBenjin, 2),
            remainingAmount: truncateDecimals(remainingAmount > 0 ? remainingAmount : 0, 2)
        })
    }
    console.log(monthPlan)
    return monthPlan;
}

//等额本金，月供利息
export function benJinMonthPay(info){
    let {amount, months, rate, returnedAmount} = info;
    if(amount == 0){
        return 0
    }
    return (amount/months)+(amount-returnedAmount)*rate/12
}

//等额本金，每月月供递减额
export function benJinMonthDiff(info) {
    let {amount, months, rate } = info;
    if(amount == 0) {
        return 0
    }
    return amount/months*rate/12
}

//等额本金，总利息
export function benJinTotalInterest(info){
    let {amount, months, rate} = info;
    if(amount == 0) {
        return 0
    }
    return ((amount/months+amount*rate/12)+amount/months*(1+rate/12))/2*months-amount;
}
//等额本息，剩余还款总额
//上月还款总额-月供总额
export function surplusAmount(info) {
    let {preAmount, monthPay} = info;
    return preAmount-monthPay
}

export function msg(title, duration = 1500, mask = false, icon = 'none') {
	//统一提示方便全局修改
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}

//判断是否为布尔值返回真假
export function isBoolean(bool) {
    return /^true$/i.test(bool)
}

export function textFormat(val) {
    if(val) {
        let newStr = val.replace(/\n/g, '_@').replace(/\r/g, '_#');
        newStr = newStr.replace(/\s/g, '&nbsp');
        return newStr
    }
}
export function vidToUrl (vid) {
    return new Promise((resolve) => {
        getVideoUrl(vid).then(data => {
            let length = data.length;
            let res_data = data.substr(13, length-14);
            res_data = JSON.parse(res_data);
            let url = res_data.vl.vi[0].ul.ui[0].url;
            let fu = res_data.vl.vi[0].fn;
            let fvkey = res_data.vl.vi[0].fvkey;
            let vurl = `${url}${fu}?vkey=${fvkey}&br=77&fmt=auto&level=0&platform=4210801&sdtfrom=v4169`;
            resolve(vurl)
        });
    })
}

const generate_key = () => {
	let dt = new Date();
	return 'feedback/'+dt.getFullYear()+'/'+(dt.getMonth()+1)+'/'+dt.getDate()+'/'+uuid();
}

export function upload_image(upload_params, filePath, name, suc_func) {
    let formData = {};
    if(upload_params.ststoken) {
        formData = {
            'key': name,
            'policy': upload_params.base64policy,
            'OSSAccessKeyId': upload_params.access_key_id,
            'signature': upload_params.signature,
            'success_action_status': '200',
            'x-oss-security-token': upload_params.ststoken
        }
    }else {
        formData = {
            'key': name,
            'policy': upload_params.base64policy,
            'OSSAccessKeyId': upload_params.access_key_id,
            'signature': upload_params.signature,
            'success_action_status': '200'
        }
    }
	const task = uni.uploadFile({
		url: upload_params.post_url,
		filePath: filePath,
		name: 'file',
		formData,
		success: (res) => {
			if (res.statusCode != 200) {
                uni.showToast({
                    icon: 'none',
                    title: '上传错误，稍后重试',
                    duration: 2000
                });
				return;
			}
			suc_func && suc_func(res);
		}
	});

	task.onProgressUpdate((res) => {
		if(res.progress < 100) {
			uni.showLoading({
				title: `上传${res.progress}%`
			})
		} else {
			uni.hideLoading()
		}

		// 测试条件，取消上传任务。
		// if (res.progress > 50) {
		// 	uploadTask.abort();
		// }
	});
}

/**
 * @desc 异步上传图片
 * @param upload_params {String} 上传参数
 * @param filePath {String} 文件路径
 * @param name {String} 上传的文件key
 * 
*/
export function asyncUploadImage(upload_params, filePath, name) {
    return new Promise((resolve, reject) => {
        uni.showLoading({
            title: '上传中...'
        })
        let formData = {
            'key': name,
            'policy': upload_params.base64policy,
            'OSSAccessKeyId': upload_params.access_key_id,
            'signature': upload_params.signature,
            'success_action_status': '200'
        };
        if(upload_params.ststoken) {
            formData['x-oss-security-token'] = upload_params.ststoken;
        }
        const task = uni.uploadFile({
            url: upload_params.post_url,
            filePath: filePath,
            name: 'file',
            formData,
            success: (res) => {
                uni.hideLoading();
                if (res.statusCode != 200) {
                    reject(res)
                    uni.showToast({
                        icon: 'none',
                        title: '上传错误，稍后重试',
                        duration: 2000
                    });
                    return;
                }
                resolve(res)
            },
            fail: (err) => {
                uni.hideLoading();
                reject(err);
                uni.showToast({
                    icon: 'none',
                    title: '网络错误，请稍后重试',
                    duration: 2000
                });
            },
            complete: (res) => {
                uni.hideLoading()
            }
        })
    })
}

/**
 * @ desc 验证是否有上传图片参数或参数是否过期,提前减去五分钟
 * @ param type {String} 上传参数 seller:顾问上传 public:普通上传 im:聊天上传 task:顾问上传任务
 * */
export function checkUploadImageParam(type='public'){
    return new Promise((resolve, reject) => {
        const indexStore = useIndexStore();

        //是否过期
        if(indexStore.uploadParam.hasOwnProperty(type)) {
            if((indexStore.uploadParam[type].createdTime + indexStore.uploadParam[type].expires*1000 - 300000) > new Date().getTime()) {
                resolve(indexStore.uploadParam[type]);
                return
            }
        }
        try {
            getUploadImageParams(type).then(res => {
                if(res.status === 0){
                    indexStore.setUploadParam({
                        ...res.detail,
                        paramType: type,
                        createdTime: new Date().getTime()
                    })
                    resolve(indexStore.uploadParam[type])
                }else {
                    reject(res.detail)
                }
            })
        } catch (error) {console.log(error)}
    })
};

/**
 * @ desc 验证置业顾问上传入驻图片参数或参数是否过期
 * @ param {string} type
 * */
export function checkUploadSellerJoinParam(type='seller'){
    return new Promise((resolve, reject) => {
        const indexStore = useIndexStore();
        
        //是否过期
        let expireFlag = indexStore.uploadParamSellerJoin && (indexStore.uploadParamSellerJoin.createdTime + indexStore.uploadParamSellerJoin.expires*1000 - 300000) > new Date().getTime();

        if(expireFlag) {
            resolve(indexStore.uploadParamSellerJoin);
            return
        }
        uploadParamsAPI(type).then(res => {
            if(res.status === 0){
                indexStore.setSellerJoinUploadParam({
                    ...res.detail,
                    createdTime: new Date().getTime()
                })
                resolve(indexStore.uploadParamSellerJoin)
            }else {
                reject(res.detail)
            }
        })
    })
};

/**
 * @ desc 验证顾问上传名片是否有上传图片参数或参数是否过期
 * */
export function checkUploadDistParam(){
    return new Promise((resolve, reject) => {
        const indexStore = useIndexStore();

        //是否过期
        let expireFlag = indexStore.uploadDistParam && (indexStore.uploadDistParam.createdTime + indexStore.uploadDistParam.expires*1000 - 300000) > new Date().getTime();

        if(expireFlag) {
            resolve(indexStore.uploadDistParam);
            return
        }
        uploadDistParams().then(res => {
            if(res.status === 0){
                indexStore.setDistParam({
                    ...res.detail,
                    createdTime: new Date().getTime()
                })
                resolve(indexStore.uploadDistParam)
            }else {
                reject(res.detail)
            }
        })
    })
};


/**
 * 验证是否存在腾讯地铁站数据
 * 腾讯地铁站数据检索直线距离内楼盘
 */
export function checkTencentMetro(cityCode){
    return new Promise((resolve, reject) => {
        const indexStore = useIndexStore();

        if(indexStore.tencentMetroMap[cityCode]) {
            resolve(indexStore.tencentMetroMap[cityCode])
        }else {
            tencentMetroAPI(cityCode).then(res => {
                if(res.status === 0) {
                    indexStore.setTencentMetroMap({city: cityCode, value: res.detail});
                    resolve(res.detail)
                }
            })
        }
    })
};

/**
 * @ desc 过滤城市数据,转化为适配三级联动菜单结构
 * @ params list {Arrary} 城市或地铁数据
 * @ params showAll {boolen} 是否显示全部
 * @ return {Array} 转化好的数据
 */
export function mapDataTocascader(info) {
    let { list, showAll=false } = info;
    let listCopy = [{
        name: '不限',
        value: ''
    }];
    list.forEach(item => {
        let childSubmenu = [];
        if(item.street&&item.street.length>0){
            item.street.forEach(child => {
                childSubmenu.push({
                    name: child,
                    value: child
                })
            })
        }
        listCopy.push({
            name: item.label,
            value: item.value,
            submenu: childSubmenu,
            showAllSub: showAll
        })
    })
    return listCopy
};

/**
 * 创建一个数组映射，将数组中每个值变为一个新的值，保存到新数组，再返回新数组
 * 如 [a,b,c] => [{label:a,value:a}, {label:b, value:b}]
 * @param {Array} arr 数组
 * @param {Function} mapper 过程
 * 使用: createMap(arr, (item) => ({label: item, value: item}))
*/
export function createMap(arr, mapper) {
    let newArr = [];
    for(let i=0; i<arr.length; i++) {
        const newItem = mapper(arr[i]);
        newArr.push(newItem)
    }
    return newArr
}

/**
 * 生成uuid
 * 
*/
export function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    return s.join("");
}

/**
 * 获取文件后缀,如.jpg
 * @param path {String} 本地文件路径
*/
export function getFileType(path) {
    let reg = /\.[^\.]+$/;
    let matches = reg.exec(path);
    if (matches) {
        return matches[0];
    }
    return '';
}

/**
 * 验证微信隐私政策授权
 * 判断API是否存在，不存在表示微信版本号过低
 * @return ture/false
*/
export function checkWXPrivacyAuthorize() {
    return new Promise((resolve, reject) => {
        if(typeof uni.getPrivacySetting === 'function') {
            uni.getPrivacySetting({
                success: res => {
                    resolve(res.needAuthorization)
                },
                fail: (err) => {
                    reject(err)
                }
            })
        }else {
            uni.showModal({
                title: '提示',
                content: '当前微信版本过低，请升级到最新微信版本',
                complete: function() {
                    resolve(false)
                }
            })
        }
    })
}

//验证token是否过期
export function check_token () {
	let token = uni.getStorageSync('token');
    if(token && token.token && (new Date()).getTime() < token.expire + token.created){
		return token.token;
	}
	return false;
}

export function clearToken() {
    return new Promise((resolve) => {
        try {
        	uni.removeStorageSync('token');
            resolve()
        } catch (e) {}
    })
}

const prePage = ()=>{
    let pages = getCurrentPages();
    let prePage = pages[pages.length - 2];
    // #ifdef H5
    return prePage;
    // #endif
    return prePage.$vm;
}

function filterArr(arr){
	let newArr = [];
	arr.map((item, index) => {
		newArr.push({
			name: item,
			value: item
		})
	})
	return newArr;
}

/**
 * @ func 格式化近期时间
 * @ params UTCtime 时间戳
 * @ parmas format 格式化规则 y-m-d h:m:s
 * @ retun 近期时间
 */
export function UTCConvertTime(UTCtime, format=''){
	let time = parseTime(UTCtime, format);
    let repliceTime = time.replace(/-/g, "/");
    let ptime = new Date(repliceTime).getTime();
    const twentyFourHours = 24 * 60 * 60 * 1000;
    const fortyEightHours = 24 * 60 * 60 * 1000 * 2;
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const today = `${year}/${month}/${day}`;
    const todayTime = new Date(today).getTime();
    const yesterdayTime = new Date(todayTime - twentyFourHours).getTime();
    const lastYesterdayTime = new Date(todayTime - fortyEightHours).getTime();
    if( ptime >= todayTime ){
        return '今天 '+time.split(' ')[1];
    }
    else if( ptime < todayTime && yesterdayTime <= ptime ){
        return '昨天 '+time.split(' ')[1];
    }
    else if( ptime < yesterdayTime && lastYesterdayTime <= ptime ){
        return '前天 '+time.split(' ')[1];
    }
    else{
        return time;
    }
}

/**
 * @ func 时间戳格式时间转换为今天/昨天/前天/日期
 * @ params UTCtime 时间戳
 * @ retun 近期时间
 */
export function timeStampConvertTime(stamp){
    if(!stamp) return '';
    let time = parseTime(stamp);
    stamp = stamp * 1000;
    const stampDate = new Date(stamp);
    const twentyFourHours = 24 * 60 * 60 * 1000;
    const fortyEightHours = 24 * 60 * 60 * 1000 * 2;
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const today = `${year}/${month}/${day}`;
    const todayTime = new Date(today).getTime();
    const yesterdayTime = new Date(todayTime - twentyFourHours).getTime();
    const lastYesterdayTime = new Date(todayTime - fortyEightHours).getTime();
    if( stamp >= todayTime ){
        return '今天 '+time.split(' ')[1];
    }
    else if( stamp < todayTime && yesterdayTime <= stamp ){
        return '昨天 '+time.split(' ')[1];
    }
    else if( stamp < yesterdayTime && lastYesterdayTime <= stamp ){
        return '前天 '+time.split(' ')[1];
    }
    else{
        let stampY = stampDate.getFullYear();
        let stampM = stampDate.getMonth()+1 < 10 ? '0'+(stampDate.getMonth()+1) : stampDate.getMonth()+1;
        let stampD = stampDate.getDate() < 10 ? '0'+stampDate.getDate() : stampDate.getDate();
        let stamph = stampDate.getHours() < 10 ? '0'+stampDate.getHours() : stampDate.getHours();
        let stampm = stampDate.getMinutes() < 10 ? '0'+stampDate.getMinutes() : stampDate.getMinutes();
        let stamps = stampDate.getSeconds() < 10 ? '0'+stampDate.getSeconds() : stampDate.getSeconds();
        return `${year===stampY?'':stampY+'/'}${stampM}/${stampD} ${stamph}:${stampm}`;
    }
}

/**
 * 距离目标日期还剩余多少天
 * ios系统必须replace(/-/g, '/') 2022-11-25 12:00:00
 * 时间戳大于0则返回有效日期，否则会返回null
 * @param dateTime {Date} 目标日期时间
 * @param past {Boolean} true:已经过去XX时间。false:距离开始xx时间
 */
export function surplusDays(dateTime, past=false) {
	let setTime = new Date(dateTime.replace(/-/g, '/'));
	let newTime = new Date();
    let restSec = past ? newTime.getTime() - setTime.getTime() : setTime.getTime() - newTime.getTime();
    if(restSec>0) {
        return {
            day: parseInt(restSec / (60*60*24*1000)),
            hour: parseInt(restSec / (60*60*1000) % 24),
            minu: parseInt(restSec / (60*1000) % 60)
        }
    }else {
        return null
    }
}

//处理区域和地铁数据
export function areaFilter(data) {
	let areaArr = [
		{
			name: "不限",
			value: ""
		}
	];
	data.map(ele => {
		areaArr.push({
			name: ele.label,
			value: ele.value,
			// submenu: filterArr(ele.street ? ele.street : ele.station)
		})
	})
	return areaArr
}

//处理省份区域组合
export function cityFilter(data){
	let city = [];
	data.map(ele => {
		city.push({
			name: ele.label,
			value: ele.value,
			submenu: areaFilter(ele.area)
		})
	})
	return city
}

//处理筛选数据，单选/多选，替换title
export function droupDownFilter (data) {
	return JSON.parse(JSON.stringify(data).replace(/title/g, 'name'))
}

export function setCity(city){
	uni.setStorage({
		key: 'city',
		data: city
	})
}

/**
 * 设置更新用户信息,再提交
 */
export function updateUserInfo(info={}){
    return new Promise((resolve, reject) => {
        const userInfoStore = useUserInfoStore();

        let data = {
            ...(userInfoStore.userInfo.id ? userInfoStore.userInfo : {}),
            ...info
        }
        submitUserInfo(data).then(res => {
            if(res.status == 0){
                userInfoStore.setUserInfo(res.detail);
                uni.setStorage({
                    key: 'userInfo',
                    data: res.detail
                })
                resolve(res.detail)
            }else{
                reject(res.detail)
            }
        })
    })
}

/**
 * 将一维数组处理为二维数组
 * @param {Array} list 需要处理的一维数组
 * @param {Array} nameKey 长度为二的数组，依序为 name 取值
 * @returns 
 */
export function convertOneDimArray(list, nameKey) {
  if (!nameKey || !Array.isArray(list)) {
    return null;
  }

  const xMap = new Map();

  list.forEach((item) => {
    const x = item[nameKey];
    const y = item;
    const xValue = xMap.get(x);
    if (!xValue) {
      xMap.set(x, {
        name: x,
        value: [y],
      });
    } else {
      xValue.value.push(y)
    }
  });

  return [...xMap.values()];
}

/**
 * 监测是否打开保存图片到相册权限
 */
export function savePhotoAuth() {
    return new Promise((resolve, reject) => {
        uni.getSetting({
            success(res) {
                if (!res.authSetting['scope.writePhotosAlbum']) {
                    uni.authorize({
                        scope: 'scope.writePhotosAlbum',
                        success() {
                            resolve()
                        },
                        fail(err) {
                            reject(err);
                            uni.showModal({
                                content: '检测到您没打开相册权限，是否去设置打开？',
                                confirmText: '确认',
                                cancelText: '取消',
                                success(succ) {
                                    if (succ.confirm) {
                                        uni.openSetting({
                                            success: succ => {}
                                        })
                                    }
                                }
                            })
                        }
                    });
                }else {
                    resolve()
                }
            },
            fail(e) {
                reject(e)
            }
        })
    })
}

/**
 * 下载单张网络图片,图片临时路径
 */
export function getTempPath(url) {
    return new Promise((resolve, reject) => {
        uni.downloadFile({
            url,
            success: res => {
                if(res.statusCode === 200) {
                    uni.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success: function(result) {
                            return resolve(res)
                        },
                        fail: function(e) {
                            reject(url+JSON.stringify(e))
                        }
                    })
                }
            },
            fail:function(err){
                reject(url+JSON.stringify(err))
            }
        })
    })
}

/**
 * 保存图片到手机
 * @param {String} url 图片地址
*/
export function saveImageToAlbum(imgSrc){
    return new Promise((resolve, reject) => {
        uni.saveImageToPhotosAlbum({
            filePath: imgSrc,
            success() {
                uni.showToast({
                    title: '图片保存成功',
                    icon: 'success',
                    duration: 2000
                })
                resolve('succ')
            },
            fail(e) {
                reject('fail')
            }
        })
    })
}

/**
 * 比较两个版本号大小
 * ver1>=ver2 返回true
 */
export function versionFunegt(ver1, ver2) {
    if(ver1 == ver2) return true;
    const vs1 = ver1.split(".").map(a => parseInt(a));
    const vs2 = ver2.split(".").map(a => parseInt(a));
    const leng = Math.min(vs1.length, vs2.length);
    for(let i=0; i<leng; i++) {
        if(vs1[i] > vs2[i]) {
            return true
        }else if(vs1[i] < vs2[i]) {
            return false
        }
    }
    if(leng == vs1.length) {
        return false
    }else {
        return true
    }
}

/**
 * @ desc 保留小数点后几位
 * @param {Number} num 要四舍五入的数字
 * @param {Number} len 小数点后几位
 */
export function getBit(num, len=2) {
    let res = parseFloat(num);
    if(isNaN(res)) {
        return 0
    }
	return parseFloat(res.toFixed(len))
}

/**
 * @desc 高并发请求，最大并发数
 * @param urls {Array} 接口url列表
 * @param maxNum {Number} 最大并发数
 */
export function concurRequest(urls=[], maxNum=3) {
    return new Promise((resolve) => {
        if(urls.length === 0) {
            resolve([]);
            return
        }
        const results = [];
        let index = 0;//下一个请求下标
        let count = 0;//请求完成数量
        async function request() {
            if(index === urls.length) {
                return
            }
            const url = urls[index];
            const i = index;
            index++;
            try{
                const resp = await baseGetRequest(url);
                results[i] = resp;
            }catch(err) {
                results[i] = err;
            }finally{
                count++;
                if(count === urls.length) {
                    resolve(results)
                }
                request();
            }
        }
        
        const times = Math.min(maxNum, urls.length);
        for(let i=0; i<times; i++) {
            request();
        }
    })
}

//数组中匹配到字符串返回下标
export function findIndexInArr(arr, str) {
    return arr.findIndex(item => item.includes(str))
}

/**
 *@desc 数组对象相同值相加去重，如数组内相同户型的套数相加再去重
 *@param arr {Array} 需要处理的数组
 *@param resultNum {String} 最终计算结果的键名
 *@param keyName {Array} 计算判断的键名
 *@param keyValue {Array} 用于计算结果的键，对应的值为number
 */
export function delSameObjValue(arr, resultNum, keyName, keyValue) {
    const wrap = new Map();
    arr.forEach(item => {
        let str = keyName.map(v => item[v]).join('_');
        item[resultNum] = keyValue.reduce((p, c) => p += item[c], 0);
        wrap.has(str) ? wrap.get(str)[resultNum] += item[resultNum] : wrap.set(str, item);
    })
    return Array.from(wrap).map(([, v]) => v);
}

/**
 * @desc 数组内随机选中几个元素，不重复，并返回
 * @param arr {Array} 原始数组
 * @param maxNum {NUmber} 返回元素个数
*/
export function randomArray(arr, maxNum=1) {
    let results = [];
    if(arr.length === 0) return [];
    if(maxNum > arr.length) {
        maxNum = arr.length;
    }
    let copyArr = arr.slice(0);
    for(let i=0; i<maxNum; i++) {
        let ran = Math.floor(Math.random() * (copyArr.length -i));
        results.push(copyArr[ran]);
        copyArr[ran] = copyArr[copyArr.length - i - 1]
    }
    copyArr = [];
    return results
}

/**
 * @desc 对象数组根据某个key去重
 * @param arr {Array} 数组
 * @param uniId {String} 指定的key
 * @test [{name:'apple',age: 9},{name:'apple',age:10}]
 * @retuen [{name:'apple',age:9}]
*/
export function uniqueFunc(arr, uniId){
    const res = new Map();
    return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1));
}

/**
 * @desc 手机号脱敏处理
 * @param {String} phone 手机号
 * @returns 137******0000
*/
export function phoneHide(phone) {
    return phone.replace(/(\d{3})\d*(\d{4})/, '$1****$2');
}

/**
 * @desc 用户姓名脱敏处理
 * @param {String} name 姓名
 * @returns 欧,欧*,欧*修,欧阳**xx
*/
export function desensitizeName(name) {
    if (!name) return '';

    if(name.length == 2){
        return name.replace(/^(.).+$/, "$1*")
    } else if(name.length == 3){
        return name.replace(/^(.).+(.)$/, "$1*$2");
    } else if(name.length > 3){
        return name.replace(/^(.{2}).+(.)$/, "$1**$2")
    }
    
    return name
}

/**
 * 移除字符串内所有空格
 * 
*/
export function trimAll(str) {
    return str.split(/[\t\r\f\n\s]*/g).join('')
}

/**
 * 判断设备类型是否为ios
*/
export function isIos() {
    const deviceInfo = uni.getDeviceInfo();
	return deviceInfo.platform === 'ios';
}

export default {
	get_query_string,
	uuid,
	setCity,
	generate_key,
	surplusDays,
    prePage,
	droupDownFilter
}

/**
 * 获取当前日期
 * @param tiems {Boolean} 是否返回时间
 */
export function getNowDate(times=false){
	//获取当前时间
	var date = new Date();
	var year = date.getFullYear();
	var month = repair(date.getMonth() + 1);
	var day = repair(date.getDate());
	var hour = repair(date.getHours());
    var minute = repair(date.getMinutes());
    var second = repair(date.getSeconds());
    if(times) {
        return `${year}-${month}-${day} ${hour}:${minute}:${second}`
    }else {
        return `${year}-${month}-${day}`
    }
}

/**
 * 小于9前边补0
 */
function repair(i) {
    if(i>=0 && i<9) {
        return '0'+i
    }else {
        return i
    }
}

/**
 * 按照指定长度分割数组为n等份
 * @param arr {Array} 一维数组
 * @param len {Number} 指定长度
 */
export function subGroup(arr, len) {
    if(arr.length === 0) return [];
    var newArr = [];
    for(let i = 0; i < arr.length; i+= len) {
        newArr.push(arr.slice(i, i+len))
    }
    return newArr
}

// 随机名称
export function getUUID () {
  return `${str4()}${str4()}-${str4()}-${str4()}-${str4()}-${str4()}${str4()}${str4()}`
}
function str4 () {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}